﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;
using System.Xml.Serialization;
using DentScan2.DB;

namespace DentScan2.WebApp.Classes
{
    public class CalcData
    {
        public AreaCalcData AreaCalcData
        {
            get;
            set;
        }

        public List<AWS> AWS
        {
            get;
            set;
        }

        public string MethodName
        {
            get;
            set;
        }

        public CalcData()
        {
            AWS = new List<AWS>();
            AreaCalcData = new AreaCalcData();
        }

        public void LoadFromDatabase(Guid areaId, int methodId)
        {
            DLDataContext dl = new DLDataContext(ConfigurationManager.ConnectionStrings["DBCONN"].ConnectionString);
            DB.Area area = dl.Areas.First(ar => ar.AreaId == areaId);
            AreaCalcData.HourPrice = area.HourPrice.Value;
            AreaCalcData.AWCurrency = area.AWCurrency;
            AreaCalcData.AWToHour = area.AWToHour.Value;
            AreaCalcData.VAT = area.VAT.Value;
            AreaCalcData.Alum = area.Alum.Value;
            AreaCalcData.DisassemblyHourPrice = area.DisassemblyHourPrice.Value;
            AreaCalcData.PreparationHourPrice = area.PreparationHourPrice.Value;
            AreaCalcData.PNPPercent = area.PNPPercent.Value;
            AreaCalcData.PolishPercent = area.PolishPercent.Value;
            if (methodId == -1)
            {
                methodId = 1;
                this.MethodName = "Почасово";
            }
            else
                this.MethodName = dl.AWMethods.First(m => m.AWMethodId == methodId).MethodName;
            foreach (AW aw in dl.AWs.Where(a => a.AWMethodId == methodId).ToArray())
            {
                AWS.Add(
                    new AWS()
                    {
                        AW = aw.AW1.Value,
                        Cnt = aw.Cnt.Value,
                        IsHorizontal = aw.IsHorizontal,
                        SizeTo = aw.SizeTo.Value
                    }
                    );
            }


        }

        public string GetSerialized()
        {
            XmlSerializer xs = new XmlSerializer(typeof(CalcData));
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            xs.Serialize(sw, this);
            return sb.ToString();
        }

        public static CalcData FromXml(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(CalcData));
            StringReader sr = new StringReader(xml);
            return (CalcData)xs.Deserialize(sr);
        }
    }
}